package com.ruoyi.web.controller.weixin;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.Map;

/**
 * @ClassName WxQrcode
 * @Description 微信小程序码下载
 * @Author leizhang
 * Date 2021/9/2 1:37 下午
 * @Version 1.0
 **/
@RequestMapping("/wxQrcodeApi")
@RestController
public class WxQrcodeApi extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(WxQrcodeApi.class);
    @Autowired
    private WxMaService wxMaService;

    @Value("${weixin.path}")
    private String path;
    @Autowired
    private RuoYiConfig ruoYiConfig;

    @PostMapping("/export")
    private AjaxResult exportQrCode(@RequestBody Map<String,Object> requestParam) {
        OutputStream out = null;
        InputStream in = null;
        String company = String.valueOf(requestParam.get("company"));
        int companyId = (int)requestParam.get("companyId");
        try {
            if (companyId == 0) {
                companyId = 1000;
            }
            //文件生成的路径
            String downloadPath = ruoYiConfig.getDownloadPath();
            String wxPath = path.concat("?cid=").concat(String.valueOf(companyId));
            File codeFile = wxMaService.getQrcodeService().createWxaCode(wxPath, 430, false, new WxMaCodeLineColor("0", "0", "0"), false);
            String[] split = codeFile.getName().split("\\.");
            String fileName = company.concat(".").concat(split[1]);
            File desc = new File(downloadPath.concat(fileName));
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
            in = new FileInputStream(codeFile);
            out = new FileOutputStream(desc);
            org.apache.commons.io.IOUtils.copy(in, out);
            return AjaxResult.success(fileName);
        } catch (WxErrorException e) {
            LOGGER.error("二维码生成失败:[{}]", e.getError(), e);
            return AjaxResult.error();
        } catch (IOException e) {
            LOGGER.error("文件输出异常:[{}]", e.getCause(), e);
            return AjaxResult.error();
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
}
